package com.supermarket.controller;

import cn.hutool.core.util.StrUtil;
import com.supermarket.common.ResponseResult;
import com.supermarket.entity.ArticleComment;
import com.supermarket.exception.ArticleException;
import com.supermarket.service.ArticleCommentService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article-comment")
public class ArticleCommentController {

    @Resource
    private ArticleCommentService articleCommentService;

    /**
     * 添加评论
     *
     * @param comment 评论对象
     * @return 包含评论ID的响应结果
     */
    @PostMapping("/add")
    public ResponseResult<Integer> addComment(@RequestBody ArticleComment comment) {
        try {
            if (StrUtil.isBlank(comment.getContent())) {
                return ResponseResult.error(400, "评论内容不能为空");
            }
            
            if (comment.getArticleId() == null) {
                return ResponseResult.error(400, "文章ID不能为空");
            }
            
            if (comment.getUserId() == null) {
                return ResponseResult.error(400, "用户ID不能为空");
            }
            
            Integer commentId = articleCommentService.addComment(comment);
            return ResponseResult.success(commentId);
        } catch (ArticleException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }

    /**
     * 删除评论
     *
     * @param id 评论ID
     * @return 包含操作结果的响应结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseResult<String> deleteComment(@PathVariable Integer id) {
        try {
            int result = articleCommentService.deleteComment(id);
            if (result > 0) {
                return ResponseResult.success("评论删除成功");
            } else {
                return ResponseResult.error(400, "评论删除失败");
            }
        } catch (ArticleException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }

    /**
     * 获取评论详情
     *
     * @param id 评论ID
     * @return 包含评论信息的响应结果
     */
    @GetMapping("/detail/{id}")
    public ResponseResult<ArticleComment> getCommentDetail(@PathVariable Integer id) {
        ArticleComment comment = articleCommentService.getCommentById(id);
        if (comment != null) {
            return ResponseResult.success(comment);
        } else {
            return ResponseResult.error(404, "评论不存在");
        }
    }

    /**
     * 获取文章评论列表
     *
     * @param articleId 文章ID
     * @return 包含评论列表的响应结果
     */
    @GetMapping("/article/{articleId}")
    public ResponseResult<List<ArticleComment>> getArticleComments(@PathVariable Integer articleId) {
        List<ArticleComment> comments = articleCommentService.getCommentsByArticleId(articleId);
        return ResponseResult.success(comments);
    }

    /**
     * 获取用户评论列表
     *
     * @param userId 用户ID
     * @return 包含评论列表的响应结果
     */
    @GetMapping("/user/{userId}")
    public ResponseResult<List<ArticleComment>> getUserComments(@PathVariable Integer userId) {
        List<ArticleComment> comments = articleCommentService.getCommentsByUserId(userId);
        return ResponseResult.success(comments);
    }

    /**
     * 获取评论回复列表
     *
     * @param parentId 父评论ID
     * @return 包含回复列表的响应结果
     */
    @GetMapping("/replies/{parentId}")
    public ResponseResult<List<ArticleComment>> getCommentReplies(@PathVariable Integer parentId) {
        List<ArticleComment> replies = articleCommentService.getRepliesByParentId(parentId);
        return ResponseResult.success(replies);
    }

    /**
     * 统计文章评论数量
     *
     * @param articleId 文章ID
     * @return 包含评论数的响应结果
     */
    @GetMapping("/count/{articleId}")
    public ResponseResult<Integer> countArticleComments(@PathVariable Integer articleId) {
        int count = articleCommentService.countCommentsByArticleId(articleId);
        return ResponseResult.success(count);
    }

    /**
     * 获取文章的一级评论
     *
     * @param articleId 文章ID
     * @return 包含一级评论的响应结果
     */
    @GetMapping("/root/{articleId}")
    public ResponseResult<List<ArticleComment>> getRootComments(@PathVariable Integer articleId) {
        List<ArticleComment> rootComments = articleCommentService.getRootCommentsByArticleId(articleId);
        return ResponseResult.success(rootComments);
    }

    /**
     * 批量获取多篇文章的根评论
     *
     * @param articleIds 文章ID列表，以逗号分隔
     * @return 包含多篇文章根评论的响应结果
     */
    @GetMapping("/batch-root")
    public ResponseResult<Map<Integer, List<ArticleComment>>> getBatchRootComments(@RequestParam("ids") String articleIds) {
        try {
            // 解析文章ID列表
            List<Integer> idList = StrUtil.split(articleIds, ',')
                    .stream()
                    .map(Integer::parseInt)
                    .toList();
            
            if (idList.isEmpty()) {
                return ResponseResult.error(400, "文章ID列表不能为空");
            }
            
            Map<Integer, List<ArticleComment>> commentMap = articleCommentService.getBatchRootComments(idList);
            return ResponseResult.success(commentMap);
        } catch (NumberFormatException e) {
            return ResponseResult.error(400, "无效的文章ID格式");
        }
    }
    
    /**
     * 批量获取多篇文章的评论树
     *
     * @param articleIds 文章ID列表，以逗号分隔
     * @return 包含多篇文章评论树的响应结果
     */
    @GetMapping("/batch-tree")
    public ResponseResult<Map<Integer, List<Map<String, Object>>>> getBatchCommentTrees(@RequestParam("ids") String articleIds) {
        try {
            // 解析文章ID列表
            List<Integer> idList = StrUtil.split(articleIds, ',')
                    .stream()
                    .map(Integer::parseInt)
                    .toList();
            
            if (idList.isEmpty()) {
                return ResponseResult.error(400, "文章ID列表不能为空");
            }
            
            Map<Integer, List<Map<String, Object>>> treeMap = articleCommentService.getBatchCommentTrees(idList);
            return ResponseResult.success(treeMap);
        } catch (NumberFormatException e) {
            return ResponseResult.error(400, "无效的文章ID格式");
        }
    }

    /**
     * 分页获取文章评论
     *
     * @param articleId 文章ID
     * @param pageNum   当前页码
     * @param pageSize  每页显示条数
     * @return 包含分页评论的响应结果
     */
    @GetMapping("/page/{articleId}")
    public ResponseResult<Map<String, Object>> getCommentsWithPagination(
            @PathVariable Integer articleId,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        
        Map<String, Object> result = articleCommentService.getCommentsWithPagination(articleId, pageNum, pageSize);
        return ResponseResult.success(result);
    }

    /**
     * 获取评论树（带用户信息）
     *
     * @param articleId 文章ID
     * @return 包含评论树的响应结果
     */
    @GetMapping("/tree/{articleId}")
    public ResponseResult<List<Map<String, Object>>> getCommentTree(@PathVariable Integer articleId) {
        List<Map<String, Object>> commentTree = articleCommentService.getCommentTree(articleId);
        return ResponseResult.success(commentTree);
    }
} 